// pages/user/reg.js

let _this;
let Bmob = require('../../utils/bmob.js');
let common = require('../../utils/common.js');
let App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userName: '',
    password: '',
    repeatPassword: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    _this = this
    Bmob.initialize("8bbd2fa87eece23337234b59c300fb2e", "0422786c4a1502011b37da0d9f437770")
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.setNavigationBarTitle({
      title: '注册',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   *  获取用户名
   */
  getUserName: function(e) {
    _this.setData({
      userName: e.detail.value
    });
  },

  /**
   * 获取密码
   */
  getPassword: function(e) {
    _this.setData({
      password: e.detail.value
    });
  },

  /**
   * 获取重复密码
   */
  getRepeatPassword: function(e) {
    _this.setData({
      repeatPassword: e.detail.value
    });
  },

  /**
   * 注册用户
   */
  reg: function() {

    if (_this.data.userName === '' || _this.data.password === '' || _this.data.repeatPassword === '') {
      App.showError('请完整填写注册信息')
      return false
    }

    if (_this.data.password !== _this.data.repeatPassword) {
      App.showError('两次输入密码不一致')
      return false
    }

    common.getOpenId(function (openId) {
      _this.createUser(openId)
    })
    
  },

  /**
   * 创建用户的Profile
   */
  createProfile: function (success) {
    let _url = 'classes/Profile'
    App._post(_url
    , {
      'durationOfStudy': 0
    }
    , function(res){
      console.log('创建用户profile:' + res.objectId)
      wx.setStorageSync('profileId', res.objectId)
      success && success(res.objectId)
    })
  },

  /**
   * 创建用户
   */
  createUser: function (openId) {
    _this.createProfile(function(profileId){
      console.log('创建用户')

      wx.showLoading({
        title: '数据处理中',
      })

      let url = 'users'
      App._post(url, {
        'username': _this.data.userName,
        'password': _this.data.password,
        'miniOpenId': openId,
        "profile": { "__type": "Pointer", "className": "Profile", "objectId": profileId }
      }, function (res) {

        if(res.code){
          wx.hideLoading()
          
          switch(res.code){
            case 202:
              App.showError('用户名已被使用，请重新填写')
              break
            default:
              App.showError('抱歉，系统发生错误')
          }
          return false
        }

        wx.setStorageSync('bmobObjectId', res.objectId)
        wx.setStorageSync('miniOpenId', openId)
        wx.setStorageSync('userName', _this.data.userName)

        console.log(res)

        wx.hideLoading()

        wx.showToast({
          title: '注册成功',
          icon: 'success',
          duration: 2000,
          success: function (res) {

            setTimeout(function(){
              wx.switchTab({
                url: '../login',
              })
            }, 1000)
          }
        })

      })
    })
  }

})